package com.diver.flinkdemo.service.impl;


import com.diver.flinkdemo.dto.xxt.C40DataVO;
import com.diver.flinkdemo.entity.xxt.CallRecord;
import com.diver.flinkdemo.mapper.mysqlMapper.CallRecordMapper;
import com.diver.flinkdemo.service.ICallRecordService;
import com.diver.flinkdemo.utils.DateUtil;
import com.diver.flinkdemo.utils.DynamicDataSourceUtil;
import com.diver.flinkdemo.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hesc
 * @since 2022-03-02
 */
@Slf4j
public class CallRecordServiceImpl implements ICallRecordService {

    private CallRecordMapper mapper;
    private SqlSession session = null;

    @Override
    public List<CallRecord> getCallRecordList(String imei, Integer limit) {
        return mapper.getCallRecordList(imei, limit);
    }

    @Override
    public void addCallRecord(C40DataVO c40DataVO) {
        try {
            session = DynamicDataSourceUtil.mysqlSessionFactory.openSession(true);
            mapper = session.getMapper(CallRecordMapper.class);
            String imei = c40DataVO.getImei();
            log.info("通话记录回调，数据:{}", c40DataVO);
            if(StringUtils.isEmpty(imei)) {
                return;
            }
            CallRecord callRecord = new CallRecord();
            callRecord.setMsgId(c40DataVO.getMsgId());
            callRecord.setDeviceId(imei);
            callRecord.setCallNum(c40DataVO.getCallNum());
            callRecord.setCallTime((c40DataVO.getCallTime() == null) ? 0: c40DataVO.getCallTime());
            String callStart = c40DataVO.getCallStart();
            if(StringUtils.isNotBlank(callStart)) {
                callRecord.setCallStart(callStart);
            } else {
                callRecord.setCallStart(DateUtil.getNowDateWholePoint("yyyyMMddHHmmSS"));
            }
            Integer callType = c40DataVO.getCallType();
            Integer callSos = c40DataVO.getCallSos();
            if(callType == null) {
                callType = 0;
            }
            if(callType == 0 || callType == 1) {
                callType = 1;
            }
            if(callSos == 1) {
                callType = 0;
            }
            callRecord.setCallType(callType);
            callRecord.setCreateTime(System.currentTimeMillis());
            mapper.insert(callRecord);
        } finally {
            endOfSession(session);
        }
    }

    public void endOfSession(SqlSession session) {
        //关闭sqlSession
        if (session != null) {
            log.info("session commit -> session close");
//            session.commit();
            session.close();
        }
    }
}
